import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:geomancy/models/auspicious_day_list_model.dart';
import 'package:geomancy/models/auspicious_time_list_model.dart';
import 'package:geomancy/models/daily_horsecope_model.dart';
import 'package:geomancy/models/huang_li_day_model.dart';
import 'package:geomancy/tools/http.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:lunar/calendar/Fu.dart';

class JIRIParamsData {
  late String startDate;
  late String endDate;
  late String status;
  late String type;
  late int page;

  JIRIParamsData({
    required this.startDate,
    required this.endDate,
    required this.status,
    required this.type,
    required this.page,
  });

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['startDate'] = startDate;
    data['endDate'] = endDate;
    data['status'] = status;
    data['type'] = type;
    data['page'] = page;
    return data;
  }
}

class CalendarAPI {
  ///每日运势
  static Future<DailyHoroscopeResult?> getDailyHoroscope(BuildContext context, String animal) async {
    try {
      final data = await Fetch.request(Method.GET, '/huangli/shengxiaoriyun/$animal', context: context);
      final result = DailyHoroscopeModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        return result.data;
      }
      return null;
    } catch(e) {
      return null;
    }
  }
  ///当日黄历
  /// 参数日期 格式：d+mm+dd。例如1月2号  参数是 d0102
  static Future<HuangLiDayItemModel?> getCurrentDay(BuildContext context, DateTime date) async {
    try {
      final month = date.month.toString().padLeft(2, '0');
      final day = date.day.toString().padLeft(2, '0');
      final data = await Fetch.request(Method.GET, '/huangli/day?day=d$month$day', context: context);
      final result = HuangLiDayModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        return result.data;
      }
      return null;
    } catch(e) {
      return null;
    }
  }
  ///择吉日(需处理数据，比较返回值的date与endDate的大小，只返回小于等于endDate的结果)
  static Future<List<AuspiciousDayItemModel>?> chooseAnAuspiciousDay(BuildContext context, JIRIParamsData params) async {
    try {
      final data = await Fetch.request(Method.POST, '/huangli/chooseAnAuspiciousDay', params: params.toJson(), context: context);
      final result = AuspiciousDayListModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        List<AuspiciousDayItemModel> tmpList = [];
        final list = result.data?.data;
        if (list != null && list.isNotEmpty) {
          for (int i = 0; i < list.length; i++) {
            final date = list[i].date?.split(' ')[0];
            if (date != null && Utils.compareDates(date, params.endDate)) {
              tmpList.add(list[i]);
            }
          }
        }
        return tmpList;
      }
      return null;
    } catch(e) {
      return null;
    }
  }
  static String sanitizeJson(String input) {
    // 1. 替换键名的无引号为双引号
    input = input.replaceAllMapped(RegExp(r'(?<=\{|,)\s*([a-zA-Z0-9_]+)\s*:'), (match) {
      return '"${match.group(1)}":';
    });

    // 3. 替换值中未用引号包裹的双引号
    input = input.replaceAllMapped(RegExp(r':\s*([a-zA-Z0-9_]+)'), (match) {
      return ': "${match.group(1)}"';
    });

    return input;
  }
  ///择吉时
  static Future<AuspiciousTimeHtmlModel?> chooseAnAuspiciousTime(BuildContext context, String date) async {
    try {
      final data = await Fetch.request(Method.GET, '/huangli/chooseAnAuspiciousTime?day=$date', context: context);
      final result = AuspiciousTimeListModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        final responseString = '''
        ${result.data!.time!}
        ''';
        // 提取 JSON 内容
        final startIndex = responseString.indexOf('{');
        final endIndex = responseString.lastIndexOf(';');
        final jsonString = responseString.substring(startIndex, endIndex);

        // 解析 JSON 字符串
        final Map<String, dynamic> parsedJson = json.decode(sanitizeJson(jsonString));

        // 映射到 Dart 模型
        final auspiciousTimeHtmlResult = AuspiciousTimeHtmlModel.fromJson(parsedJson);
        return auspiciousTimeHtmlResult;
      }
      return null;
    } catch(e) {
      return null;
    }
  }
}